package com.tfjybj.itoo.exam.provider.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.dmsdbj.itoo.tool.base.service.impl.BaseServicePlusImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tfjybj.itoo.exam.entity.TemplateDetailsCustomEntity;
import com.tfjybj.itoo.exam.entity.TemplateDetailsEntity;
import com.tfjybj.itoo.exam.entity.TemplateDetailsExtractEntity;
import com.tfjybj.itoo.exam.entity.TemplateEntity;
import com.tfjybj.itoo.exam.model.*;
import com.tfjybj.itoo.exam.provider.dao.TemplateDao;
import com.tfjybj.itoo.exam.provider.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * TemplateService接口实现类
 * ${base}表
 *
 * @author 任晓帅
 * @version 2.0.0
 * @since 2.0.0 2018-11-15 19:40:28
 */
@Slf4j
@Service("templateService")
public class TemplateServiceImpl extends BaseServicePlusImpl<TemplateDao, TemplateEntity> implements TemplateService {

    private static final String TEMPLATEDETAIL_REDIS_INFO = "TEMPLATEDETAIL_REDIS_INFO";
    //region 模板生成
    @Resource
    private TemplateDao templateDao;
    @Resource
    private TemplateService templateService;
    @Resource
    private TemplateDetailsService templateDetailsService;
    @Resource
    private TemplateDetailsCustomService templateDetailsCustomService;
    @Resource
    private TemplateDetailsExtractService templateDetailsExtractService;
    @Resource
    private OnlineExamService onlineExamService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private QuestionService questionService;
    @Resource
    private OptionService optionService;

    @Override
    public PageInfo<TemplateModel> queryByLikeName(String name, Integer pageNum, Integer pageSize, String courseId) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(templateDao.queryLikeName(courseId, name));
    }


    //endregion

    /* **********************************以下为非模板生成的内容********************************* */

    @Override
    public PageInfo<TemplateModel> queryByOperator(String operator, Integer pageNum, Integer pageSize, String courseId) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(templateDao.queryByOperator(operator, courseId, null));
    }

    @Override
    public List<TemplateModel> queryByTemplateTypeModel(String operator, String organizingType, String startTime, String endTime) {

        return templateDao.queryByMethodAndTime(operator, organizingType, startTime, endTime);

    }


    @Override
    public List<TemplateEntity> queryAllOrganization() {
        return templateDao.queryAllOrganization();
    }

    @Override
    public List<TemplateEntity> queryByMethodOperator(String operator, String organizingType) {

        return templateDao.queryByMethodOperator(operator, organizingType);
    }

    @Override
    public TemplateModel selectTempModel(String templateId) {
        TemplateModel template = new TemplateModel();
        TemplateEntity templateEntity = templateDao.selectById(templateId);
        if (templateEntity == null) {
            log.error("templateEntity is null(模板实体为空),模板id为templateId-{}", templateId);
            return null;
        }
        BeanUtils.copyProperties(templateEntity, template);
        return template;
    }

    @Override
    public TemplateEntity queryExamStudentExamtem(String templateId) {
        return templateDao.queryExamStudentExamtem(templateId);
    }

    /**
     * 添加template
     *
     * @return 添加template
     * @author 杨海云
     * @since 2.0.0 2018年11月25日16:57:52
     */
    @Override
    @Transactional(rollbackOn = Exception.class)
    public String insertTemplate(@RequestBody TemplateModel model) {
        TemplateEntity templateEntity = new TemplateEntity();
        BeanUtils.copyProperties(model, templateEntity);
        if ("".equals(templateEntity.getId())) {
            templateEntity.setId(IdWorker.getIdStr());
        }

        for (TemplateDetailsModel templateDetailsModel : model.getTemplateDetailsModel()) {
            TemplateDetailsEntity templateDetailsEntity = new TemplateDetailsEntity();
            BeanUtils.copyProperties(templateDetailsModel, templateDetailsEntity);
            templateDetailsEntity.setTemplateId(templateEntity.getId());
            templateDetailsEntity.setId(IdWorker.getIdStr());
            this.templateDetailsService.installTemp(templateDetailsEntity);
            if (templateDetailsModel.getIsCustom() == 1) {
                for (TemplateDetailsCustomModel templateDetailsCustomModel : templateDetailsModel.getTemplateDetailsCustomModel()) {
                    TemplateDetailsCustomEntity templateDetailsCustomEntity = new TemplateDetailsCustomEntity();
                    BeanUtils.copyProperties(templateDetailsCustomModel, templateDetailsCustomEntity);
                    templateDetailsCustomEntity.setTemplateDetailsId(templateDetailsEntity.getId());
                    templateDetailsCustomEntity.setId(IdWorker.getIdStr());
                    this.templateDetailsCustomService.installTemp(templateDetailsCustomEntity);
                }
            }
            if (templateDetailsModel.getIsExtract() == 1) {
                for (TemplateDetailsExtractModel templateDetailsExtractModel : templateDetailsModel.getTemplateDetailsExtractModel()) {
                    TemplateDetailsExtractEntity templateDetailsExtractEntity = new TemplateDetailsExtractEntity();
                    BeanUtils.copyProperties(templateDetailsExtractModel, templateDetailsExtractEntity);
                    templateDetailsExtractEntity.setTemplateDetailsId(templateDetailsEntity.getId());
                    templateDetailsExtractEntity.setId(IdWorker.getIdStr());
                    this.templateDetailsExtractService.installTemp(templateDetailsExtractEntity);
                }
            }
        }
        this.templateDao.insert(templateEntity);
        String templateId = templateEntity.getId();
        return templateId;
    }

    /**
     * 添加固定抽题template--随堂小练用
     *
     * @return 返回 examPaperModel
     * @author 任蒙蒙
     * @since 2019-1-29 22:20:57
     */
    @Override
    @Transactional(rollbackOn = Exception.class)
    public ExamPaperModel insertTemplateForFix(@RequestBody TemplateModel model) {
        TemplateEntity templateEntity = new TemplateEntity();
        BeanUtils.copyProperties(model, templateEntity);
        if ("".equals(templateEntity.getId())) {
            templateEntity.setId(IdWorker.getIdStr());
        }
        String operator = model.getOperator();
        for (TemplateDetailsModel templateDetailsModel : model.getTemplateDetailsModel()) {
            TemplateDetailsEntity templateDetailsEntity = new TemplateDetailsEntity();
            BeanUtils.copyProperties(templateDetailsModel, templateDetailsEntity);
            templateDetailsEntity.setTemplateId(templateEntity.getId());
            templateDetailsEntity.setId(IdWorker.getIdStr());
            templateDetailsEntity.setOperator(operator);
            this.templateDetailsService.installTemp(templateDetailsEntity);
            if (templateDetailsModel.getIsCustom() == 1) {
                for (TemplateDetailsCustomModel templateDetailsCustomModel : templateDetailsModel.getTemplateDetailsCustomModel()) {
                    TemplateDetailsCustomEntity templateDetailsCustomEntity = new TemplateDetailsCustomEntity();
                    BeanUtils.copyProperties(templateDetailsCustomModel, templateDetailsCustomEntity);
                    templateDetailsCustomEntity.setTemplateDetailsId(templateDetailsEntity.getId());
                    templateDetailsCustomEntity.setId(IdWorker.getIdStr());
                    this.templateDetailsCustomService.installTemp(templateDetailsCustomEntity);
                }
            }
        }
        this.templateDao.insert(templateEntity);
        String courseId = model.getCourseId();
        String templateId = templateEntity.getId();

        ExamPaperModel examPaperModel = onlineExamService.queryQuestionForFix(courseId, templateId, operator);
        if (examPaperModel == null) {
            log.error("examPaperModel is null,固定抽题失败!courseId-{},templeatId-{},operator-{}", courseId, templateId, operator);
            return null;
        }

        boolean flag = updateExtractCustomForFix(templateId, operator);
        if (flag == true) {
            String detailKey = TEMPLATEDETAIL_REDIS_INFO + "_" + templateId;
            redisTemplate.delete(detailKey);

            List<ExamTemPaperQuestionTypeModel> paperQuestionTypeList = examPaperModel.getPaperQuestionTypeList();
            if (paperQuestionTypeList == null || paperQuestionTypeList.size() == 0) {
                log.error("paperQuestionTypeList is null,固定抽题的试卷中题型列表为空");
                return null;
            }
            TemplateDetailsExtractEntity templateDetailsExtractEntity = new TemplateDetailsExtractEntity();
            for (ExamTemPaperQuestionTypeModel paperQuestionType : paperQuestionTypeList) {

                List<QuestionMainModel> questionModelList = paperQuestionType.getQuestionMainModelList();
                String questionTypeId = paperQuestionType.getQuestionTypeId();
                if (questionModelList == null || questionModelList.size() == 0 || questionTypeId == null) {
                    log.error("questionModelList is null or questionTypeId is null,固定抽题的试卷中该题型下的试题列表为空或题型id为空,templateId-{},courseId-{},operator-{}", templateId, courseId, operator);
                    return null;
                }
                String temlateDetailsId = selectTemplateDetailIdForFix(templateId, questionTypeId);
                for (QuestionMainModel questionMainModel : questionModelList) {
                    String questionId = questionMainModel.getQuestionId();
                    if (questionId == null) {
                        log.error("questionId is null,固定抽题的试卷中该试题为空,该题为-{}", questionId);
                        return null;
                    }
                    templateDetailsExtractEntity.setQuestionId(questionId);
                    templateDetailsExtractEntity.setTemplateDetailsId(temlateDetailsId);
                    templateDetailsExtractEntity.setOperator(operator);
                    templateDetailsExtractEntity.setId("");
                    this.templateDetailsExtractService.installTemp(templateDetailsExtractEntity);
                }
            }

        } else {
            log.error("固定抽题时将抽出来的试题插入必抽题表失败,templeatId-{},courseId-{},operator-{}", templateId, courseId, operator);
            return null;
        }
        return examPaperModel;
    }

    /**
     * 查询模板明细id(随堂小练固定抽题用)
     *
     * @param templateId     模板id
     * @param questionTypeId 题型id
     * @return String
     * @author 任蒙蒙
     * @since 2019-1-30 10:36:05
     */
    public String selectTemplateDetailIdForFix(String templateId, String questionTypeId) {
        return templateDao.selectTemplateDetailIdForFix(templateId, questionTypeId);
    }

    /**
     * 更新IsExtract字段为1(随堂小练固定抽题用)
     *
     * @param templateId 模板id
     * @param operator   操作人
     * @return boolean
     * @author 任蒙蒙
     * @since 2019-1-30 10:36:05
     */
    public boolean updateExtractCustomForFix(String templateId, String operator) {
        return templateDao.updateExtractCustomForFix(templateId, operator);
    }

    @Override
    public PageInfo<TemplateEntity> queryTemplateByLikeNameAndOperator(String name, String operator, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(templateDao.queryTemplateByLikeNameAndOperator(name, operator));
    }

    @Override
    public List<Integer> queryCompletion(String questionTypeId, String operator, String questionClassifyId, String courseId) {

        List<QuestionModel> questionModelList = templateDao.queryQuestion(questionTypeId, operator, questionClassifyId, courseId);
        int simple = 0;
        int midding = 0;
        int hard = 0;
        if (questionModelList == null) {
            log.warn("questionModelList is null questionTypeId-{ } questionClassifyId{} ", questionTypeId, questionClassifyId);
            return null;
        }
        for (QuestionModel questionModel : questionModelList) {
            if (questionModel.getDegreeInitial() == 1) {
                simple += questionModel.getOptionCount();
            } else if (questionModel.getDegreeInitial() == 2) {
                midding += questionModel.getOptionCount();
            } else if (questionModel.getDegreeInitial() == 3) {
                hard += questionModel.getOptionCount();
            }
        }
        List<Integer> aggregate = new ArrayList<>();
        aggregate.add(simple);
        aggregate.add(midding);
        aggregate.add(hard);
        return aggregate;
    }

    @Override
    public List<QuestionTypeModel> queryQuestionType(String courseId, String operator) {
        return templateDao.queryQuestionType(courseId, operator);
    }

    @Override
    public boolean updataTemplate(String id, String status) {
        return templateDao.updataTemplate(id, status);
    }

    /**
     * 根据课程id,操作人,模板使用状态查询所有模板
     *
     * @param operator   操作人
     * @param courseId   课程id
     * @param tempStatus 模板状态
     * @return 返回符合条件的集合
     * @author maying
     * @since 2019-1-26 10:36:05
     */
    @Override
    public List<TemplateModel> selectAllTemplate(String operator, String courseId, Integer tempStatus) {
        return templateDao.queryByOperator(operator, courseId, tempStatus);
    }

    /**
     * 随堂小连随机抽题插入方法
     *
     * @param templateModelList 模板,模板明细,模板明细必抽题
     * @return 返回true/false
     * @author 马莹
     * @since 2019-2-9 17:04:08
     */
    @Transactional(rollbackOn = Exception.class)
    @Override
    public String installRandomQuestions(TemplateModel templateModelList) {
        // 模板id
        String templateId = IdWorker.getIdStr();
        final boolean[] flag = {false};
        /**
         * 1.先插入模板表获取id,拿着模板表中的id插入模板题型明细表,拿着模板题型明细表id插入模板明细必抽题表
         */
        // 声明模板实体,用于获取前端传过来的模板信息
        TemplateEntity templateEntity = new TemplateEntity();
        BeanUtils.copyProperties(templateModelList, templateEntity);
        templateEntity.setId(templateId);
        if (this.save(templateEntity)) {
            List<TemplateDetailsModel> tempDetaList = templateModelList.getTemplateDetailsModel();
            // 循环接收模板明细信息
            tempDetaList.forEach(
                    (TemplateDetailsModel templateDetailsModel) -> {
                        TemplateDetailsEntity templateDetailsEntity = new TemplateDetailsEntity();
                        BeanUtils.copyProperties(templateDetailsModel, templateDetailsEntity);
                        templateDetailsEntity.setTemplateId(templateId);
                        String tempDetailsId = IdWorker.getIdStr();
                        templateDetailsEntity.setId(tempDetailsId);
                        if (templateDetailsService.installRandomQuestions(templateDetailsEntity)) {
                            List<TemplateDetailsExtractEntity> tempDEList = new ArrayList<>();
                            templateDetailsModel.getTemplateDetailsExtractModel().forEach(
                                    templateDetailsExtractModel -> {
                                        TemplateDetailsExtractEntity templateDetailsExtractEntity = new TemplateDetailsExtractEntity();
                                        templateDetailsExtractModel.setTemplateDetailsId(tempDetailsId);
                                        BeanUtils.copyProperties(templateDetailsExtractModel, templateDetailsExtractEntity);
                                        tempDEList.add(templateDetailsExtractEntity);
                                    }
                            );
                            flag[0] = templateDetailsExtractService.installRandomQuestions(tempDEList);
                        }
                    }
            );
        }
        if (flag[0]) {
            return templateId;
        } else {
            return null;
        }

    }

    /**
     * 查询模板名称是否重复
     *
     * @param name
     * @return 模板名称是否重复
     * @author 贾建清
     * @since 2.0.0 2019-2-19 16:10:38
     */
    @Override
    public List<TemplateModel> queryTemplateName(String name) {
        return templateDao.queryTemplateName(name);
    }

    @Override
    public boolean updateTemplateById(String id) {

        boolean flagId = templateService.removeById(id);
        if (templateDao.selectDetailCount(id) > 0) {
            List<String> templateDetailIdList = templateDetailsService.getByTemplateId(id);
            boolean flagDetail = true;
            boolean flagCustom = true;
            boolean flagExtract = true;
            for (String templateDetailId : templateDetailIdList) {
                flagDetail = templateDetailsService.removeById(templateDetailId) & flagDetail;
                if (templateDao.selectCountByDetail(templateDetailId) > 0) {
                    List<String> tempalteDetailCustomIdList = templateDao.getByTemplateId(templateDetailId);
                    for (String tempalteDetailCustomId : tempalteDetailCustomIdList) {
                        flagCustom = templateDetailsCustomService.removeById(tempalteDetailCustomId) && flagCustom;
                    }
                } else {
                    flagCustom = true;
                }
                if (templateDao.selectCountExtract(templateDetailId) > 0) {
                    List<String> templateDetailExtractIdList = templateDao.getByTemplate(templateDetailId);
                    for (String templateDetailExtractId : templateDetailExtractIdList) {
                        flagExtract = templateDetailsExtractService.removeById(templateDetailExtractId) && flagExtract;
                    }
                } else {
                    flagExtract = true;
                }
            }
            return flagId && flagDetail && flagCustom && flagExtract;
        } else {
            return flagId;
        }
    }

    /**
     * 替换Redis中的题目
     *
     * @param templateId templateId
     * @return ITOO
     * @author 郭凯
     * @since 2.0.0 2019-2-24 19:58:11
     */
    @Override
    public boolean updateTemplateByQuestionId(String templateId, String courseId, String operator, String newQuestionId, String oldQuestionId) {
        String key = "practicetemplateId=" + templateId + "courseId" + courseId + "operator" + operator;
        QuestionMainModel newQuestionModel = questionService.selectNewQuestionModel(newQuestionId);
        ExamPaperModel examPaperModel = null;
        ExamPaperModel examPaperModelNew = null;
        try {
            examPaperModel = (ExamPaperModel) redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            log.error("redis中key为" + key + "查询失败", e.getMessage());
        }
        List<ExamTemPaperQuestionTypeModel> examTemPaperQuestionTypeModelList = examPaperModel.getPaperQuestionTypeList();
        for (ExamTemPaperQuestionTypeModel examTemPaperQuestionTypeModel : examTemPaperQuestionTypeModelList) {
            List<QuestionMainModel> questionMainModelList = examTemPaperQuestionTypeModel.getQuestionMainModelList();
            for (QuestionMainModel model : questionMainModelList) {
                if (oldQuestionId.equals(model.getQuestionId())) {
                    questionMainModelList.set(questionMainModelList.indexOf(model), newQuestionModel);
                    ExamTemPaperQuestionTypeModel examTemPaperQuestionTypeModelNew = examTemPaperQuestionTypeModel.setQuestionMainModelList(questionMainModelList);
                    examTemPaperQuestionTypeModelList.set(examTemPaperQuestionTypeModelList.indexOf(examTemPaperQuestionTypeModel), examTemPaperQuestionTypeModelNew);
                    examPaperModelNew = examPaperModel.setPaperQuestionTypeList(examTemPaperQuestionTypeModelList);
                }
            }
        }
        redisTemplate.opsForValue().set(key, examPaperModelNew);

        boolean temflag = templateDetailsExtractService.updateQuestionId(oldQuestionId, newQuestionId);
        if (temflag == true) {
            log.info("修改的错题是模板必抽题,将新题更新到模板必抽题表成功");
        } else {
            log.warn("修改的错题不是模板必抽题或是模板必抽题,将新题更新到模板必抽题表失败");
        }

        return temflag;
    }

    @Override
    public List<TemplateModel> queryByMethodOperatorandOrganizingType(String operator, String organizingType) {
        return templateDao.queryByMethodOperatorandOrganizingType(operator, organizingType);
    }


    /**
     * 根据模板id查询模板信息
     *
     * @param id 模板id
     * @return 模板信息
     * @author 贾建清
     * @since 2.0.0 2019-2-26 17:12:46
     */
    @Override
    public List<TemplateInfoModel> queryTemplateInfo(String id) {
        List<TemplateInfoModel> templateInfoModelList = templateDao.queryTemplateInfo(id);

//        double simple = 0.0d;
//        double secondary = 0.0d;
//        double difficulty = 0.0d;
//
//        for (int i = 0; i < templateInfoModelList.size(); i++) {
//            if (i > 0 && templateInfoModelList.get(i).getDegree().equals(templateInfoModelList.get(i - 1).getDegree())) {
//                templateInfoModelList.get(i).setQuestionCustomNumber(templateInfoModelList.get(i).getQuestionCustomNumber() + templateInfoModelList.get(i - 1).getQuestionCustomNumber());
//
//            }
//            if (templateInfoModelList.get(i).getDegree().equals(1)) {
//                simple = Double.parseDouble(templateInfoModelList.get(i).getQuestionCustomNumber().toString()) / Double.parseDouble(templateInfoModelList.get(i).getTotalNumber().toString()) * 100;
//
//            } else if (templateInfoModelList.get(i).getDegree().equals(2)) {
//                secondary = Double.parseDouble(templateInfoModelList.get(i).getQuestionCustomNumber().toString()) / Double.parseDouble(templateInfoModelList.get(i).getTotalNumber().toString()) * 100;
//                System.out.println(templateInfoModelList.get(i).getQuestionCustomNumber());
//            } else if (templateInfoModelList.get(i).getDegree().equals(3)) {
//                difficulty = Double.parseDouble(templateInfoModelList.get(i).getQuestionCustomNumber().toString()) / Double.parseDouble(templateInfoModelList.get(i).getTotalNumber().toString()) * 100;
//            } else {
//                log.error("没有符合难度等级的条件！");
//            }
//        }
//        for (TemplateInfoModel templateInfoModel : templateInfoModelList) {
//            if (templateInfoModel.getDegree().equals(1)) {
//                templateInfoModel.setTxtSimple(simple);
//            }
//            if (templateInfoModel.getDegree().equals(2)) {
//                templateInfoModel.setTxtSecondary(secondary);
//            }
//            if (templateInfoModel.getDegree().equals(3)) {
//                templateInfoModel.setTxtDifficulty(difficulty);
//            } else {
//                log.error("没有相关难度等级！");
//            }
//        }

        return templateInfoModelList;
    }

    /**
     * @param ids
     * @return
     * @author 李青松
     * @since 2.0.0 2019-2-26 17:12:46
     */
    @Override
    public List queryByQuestionId(String[] ids) {
//        QuestionAddModel questionModel=new QuestionAddModel();
        QuestionAddModel questionModel;
        List questionsModel= new ArrayList();
        for (String id:ids){
            questionModel=questionService.queryById(id);
            questionModel.setOptionModel(optionService.queryById(id));
            questionsModel.add(questionModel);
        }
        return questionsModel;
    }

}

